<template>
     <div id="app" class="container">
    <div class="chat-container">
      <div class="chat-history" ref="chatHistory">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="{ 'user-message': message.sender === 'user', 'ai-message': message.sender === 'ai' }">
          <p>{{ message.text }}</p>
        </div>
      </div>
      <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="输入消息..." class="chat-input" />
      <button @click="newChat" class="new-chat-button">新建对话</button>
    </div>
    <div class="previous-topics">
      <h3>以前的话题</h3>
      <ul>
        <li v-for="(topic, index) in previousTopics" :key="index" @click="loadTopic(topic)">
          {{ topic.title }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const messages = ref(JSON.parse(localStorage.getItem('chatHistory') || '[]'));
const userInput = ref('');
const chatHistory = ref(null);
const previousTopics = ref(JSON.parse(localStorage.getItem('previousTopics') || '[]'));

const sendMessage = () => {
  if (userInput.value.trim() !== '') {
    messages.value.push({ text: userInput.value, sender: 'user' });
    saveChatHistory();
    aiReply(userInput.value);
    userInput.value = '';
  }
};

const aiReply = (userMessage) => {
  const reply = `AI: 收到消息 - "${userMessage}"`;
  setTimeout(() => {
    messages.value.push({ text: reply, sender: 'ai' });
    saveChatHistory();
    scrollToBottom();
  }, 500);
};

const newChat = () => {
  messages.value = [];
  userInput.value = '';
  scrollToBottom();
};

const loadTopic = (topic) => {
  messages.value = topic.messages;
  scrollToBottom();
};

const saveChatHistory = () => {
  localStorage.setItem('chatHistory', JSON.stringify(messages.value));
  updatePreviousTopics();
};

const updatePreviousTopics = () => {
  const currentTopic = {
    title: `对话于 ${new Date().toLocaleDateString()}`,
    messages: messages.value
  };
  previousTopics.value.push(currentTopic);
  localStorage.setItem('previousTopics', JSON.stringify(previousTopics.value));
};

const scrollToBottom = () => {
  if (chatHistory.value) {
    chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
  }
};

onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.chat-container {
  width: 600px;
  height: 400px;
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
}

.chat-input {
  border: none;
  padding: 10px;
  width: 100%;
}

.message {
  max-width: 70%;
  margin-bottom: 10px;
  padding: 5px;
  border-radius: 5px;
}

.user-message {
  background-color: #DCF8C6;
  align-self: flex-end;
}

.ai-message {
  background-color: #F4F4F9;
  align-self: flex-start;
}
</style>